#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tack.db import query
from tack.lib import string_app, content_headers, status_codes
from tack.lib.jsontools import json_dumps
from tack.lib.dicttools import query_to_list
import time

sql_statement_feedback = '''
SELECT fb_id, post_date, referring_login, referring_url, referring_application, referring_email, comment
FROM feedback
'''

sql_statement_feedback_data = '''
SELECT fb_id, post_date, referring_login, referring_url, referring_application, referring_email, comment
FROM feedback
WHERE fb_id = %(key)s
'''

sql_statement_feedback_add = '''
INSERT INTO feedback (post_date, referring_login, referring_url, referring_application, referring_email, comment)
VALUES ( getdate(), '%(login)s', '%(url)s', '%(app)s', '%(email)s', '%(comment)s')
'''

sql_statement_feedback_delete = '''
DELETE FROM feedback WHERE fb_id = %(key)s
'''

def fetch(environ, start_response):
    sql_statement = sql_statement_feedback
    rows = query(environ['connection'], sql_statement)
    output = {}
    labels = ['fb_id', 'post_date', 'referring_login', 'referring_url', 'referring_application', 'referring_email', 'comment'] 
    output['feedback'] = query_to_list(rows, labels)
    output = json_dumps(output, indent=2)
    return string_app(output)(environ, start_response)

def fetch_key(environ, start_response):
    key = environ['dispatcher.groups']['key']
    sql_statement = sql_statement_feedback_data % locals()
    rows = query(environ['connection'], sql_statement)
    output = {}
    labels = ['fb_id', 'post_date', 'referring_login', 'referring_url', 'referring_application', 'referring_email', 'comment'] 
    output['feedback'] = query_to_list(rows, labels)
    output = json_dumps(output, indent=2)
    return string_app(output)(environ, start_response)

def add_entry(environ, start_response):
    login = environ['form']['login']
    url = environ['form'].get('url', environ.get('HTTP_REFERRER', ''))
    email = environ['form']['email']
    app = environ['form']['application']
    comment = environ['form']['comment']
    sql_statement = sql_statement_feedback_add % locals()
    query(environ['connection'], sql_statement)
    rows = query(environ['connection'], 'SELECT @@IDENTITY')
    output = json_dumps(rows, indent=2)
    return string_app(output)(environ, start_response)
    
def delete_entry(environ, start_response):
    key = environ['dispatcher.groups']['key']
    sql_statement = sql_statement_feedback_delete % locals()
    rows = query(environ['connection'], sql_statement)
    output = 'Comment Deleted'
    return string_app(output)(environ, start_response)
